package von.seiji.cn.test;

import cn.hutool.core.io.FileUtil;
import org.junit.Test;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.stream.IntStream;

public class 图片分割 {

    @Test
    public void test() throws IOException {


        String filepath = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\SeiJi.jpg";

        String outpath = "D://LL/";

        int size = 200;
        int num = 9;


        ImageInputStream stream = ImageIO.createImageInputStream(new FileInputStream(filepath));

        String suffix = FileUtil.extName(filepath);

        // ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
        String[] formatNames = ImageIO.getReaderFormatNames();

        // 依据图片类型获取该种类型的ImageReader
        ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
        reader.setInput(stream, true);
        ImageReadParam param = reader.getDefaultReadParam();

        if (Arrays.asList(formatNames).contains(suffix)) {

            int end = (int) Math.sqrt(num);
            // 行
            IntStream.range(0, end).forEach(item -> {
                //列
                IntStream.range(0, end).forEach(item1 -> {
                    int index = item * 3 + item1 + 1;

                    System.out.println("正在截取第" + index + "张图片[位置：第" + (item + 1) + "行第" + (item1 + 1) + "列]");

                    Rectangle rect = new Rectangle(item1 * size, item * size, size, size);

                    param.setSourceRegion(rect);

                    BufferedImage bi = null;
                    try {
                        bi = reader.read(0, param);
                        ImageIO.write(bi, suffix, new File(outpath + index + "." + suffix));
                    } catch (IOException e) {
                        System.err.println(e.getMessage());
                    }


                });
            });


            System.out.println("完成！！！");
        } else {
            System.err.println("不支持的图片格式！");
        }

    }

    @Test
    public void test1() throws IOException {

        String filepath = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\SeiJi.jpg";

        String outpath = "D://LL/555.png";

        BufferedImage read = ImageIO.read(new File(filepath));
        BufferedImage subimage = read.getSubimage(0, 0, 200, 200);
        boolean png = ImageIO.write(subimage, "png", new File(outpath));
        System.out.println("完成");
    }


}
